<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-21 15:55:09
 * @LastEditTime: 2020-03-27 19:26:19
 * @LastEditors: Please set LastEditors
 -->
 <style>
 
 .kafukaConfiger{
    position: relative;
    top: -10px;
    font-size: 12px;
    color: #515a6e;
    font-weight: 700;
 }
 </style>
<template>
    <div >
        
        <div style="text-align:left;overflow: auto;">
            <Button   type="primary" @click="addConfigureBt = true;addConfigureBtTitle = '新增配置';cancelsmtConfigureInfo('formValidate')">
                <Icon type="md-add" />
                创建配置
            </Button>
            <Input suffix="ios-search" placeholder="请输入名称" clearable style="width: auto" v-model="btnNameValue"
                   @on-change="connfigerCurrentPage=1;getQgaReadLoopInfoList()"/>
            <Select filterable  v-model="configerSystypeOfReach" filterable transfer  style="width:180px;" clearable placeholder="请选择系统" @on-change="connfigerCurrentPage=1;getQgaReadLoopInfoList()">
                <Option value="linux">Linux</Option>
                <Option value="windows">Windows</Option>
            </Select>
            <DatePicker type="daterange" transfer  placeholder="请选择日期" style="width: 200px"
                        :editable="false"
                        v-model="configerDateSelected" @on-change="dateSelected" :options="options3"></DatePicker>
            <Select filterable  v-model="configerTimeIntervalOfReach" filterable  transfer  style="width:180px;" clearable placeholder="请选择采集周期"
                     v-if="readType == 'qga_loop_read'"
                     @on-change="connfigerCurrentPage=1;getQgaReadLoopInfoList()">
                <Option value="5">5S</Option>
                <Option value="10">10S</Option>
                <Option value="30">30S</Option>
                <Option value="45">45S</Option>
                <Option value="60">60S</Option>
            </Select>
            <!-- <Button type="primary"  @click="getQgaReadLoopInfoList">搜索</Button> -->
            <Page :total="pageCount" show-total style="float:right;" show-elevator  show-sizer :current="connfigerCurrentPage" :page-size="configerItemPage"   @on-change="switchineConfigerCurrentPage" @on-page-size-change="switchConfigerItemPage" transfer/>
        </div>
        <Table  :columns="tbTitle" :data="tbData" style="margin-top:10px; overflow: unset;"
                :show-header="true" ></Table>
        <Modal v-model="addConfigureBt" :title="addConfigureBtTitle" :loading="loading" :mask-closable="false"
                @on-ok="submitConfigureInfo('formValidate')"  @on-cancel="cancelsmtConfigureInfo('formValidate')">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="95">
                <FormItem label="名称" prop="name">
                    <Input v-model="formValidate.name" placeholder="请输入名称" :maxlength="64"></Input>
                </FormItem>
                <FormItem label="操作系统" prop="osType">
                    <RadioGroup v-model="formValidate.osType">
                        <Radio label="Windows">Windows</Radio>
                        <Radio label="Linux">Linux</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="读取路径" prop="path">
                    <Input v-model="formValidate.path" placeholder="请输入读取路径"></Input>
                </FormItem>
                <!-- <span class="kafukaConfiger">发送KAFKA配置:</span>
                <FormItem label="地址" prop="kafka_addr">
                    <Input v-model="formValidate.kafka_addr" placeholder="请输入配置发送KAFKA地址"></Input>
                </FormItem>
                <FormItem label="TOPIC" prop="kafka_topic">
                    <Input v-model="formValidate.kafka_topic" placeholder="请输入配置发送TOPIC配置"></Input>
                </FormItem> -->
                <!-- <FormItem label="读取方式" prop="read_way">
                    <RadioGroup v-model="formValidate.read_way">
                        <Radio label="0">单次</Radio>
                        <Radio label="1">循环</Radio>
                    </RadioGroup>
                </FormItem> -->
                <FormItem label="读取周期" prop="gap" v-show="this.readType=='qga_loop_read'">
                    <RadioGroup v-model="formValidate.gap">
                        <Radio label="5">5秒</Radio>
                        <Radio label="10">10秒</Radio>
                        <Radio label="30">30秒</Radio>
                        <Radio label="45">45秒</Radio>
                        <Radio label="60">60秒</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="可见性" prop="visibility">
                    <RadioGroup v-model="formValidate.visibility" >
                        <!-- <Radio label="public" >公共</Radio> -->
                        <Radio label="share" >共享</Radio>
                        <Radio label="private">私有</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="描述" prop="description">
                    <Input v-model="formValidate.description" type="textarea" :rows="2" :maxlength="200"></Input>
                </FormItem>
            </Form>
        </Modal>

        <Modal v-model="delConfigureMd" title="删除配置" @on-ok="ok4delConfigureMd">
            <div style="text-align:center;font-size:15px;">确认要删除配置：" <strong>{{this.currConfigureName}}</strong> " 吗？</div>
        </Modal>
        <Modal v-model="detailConfigureMd" title="配置详情" >
             <Table stripe :columns="detailTbTitle" :data="detailTbData" :show-header="false"></Table>
        </Modal>
    </div>
</template>
<script>
    import axios from '@/libs/axios1'
    import TableTooltip from '@/view/drill_compete/page/tableTooltip.vue';
    export default {
        name:'qgaReadLoopCollect',
        components:{TableTooltip},
        data(){
            const validateName = (rule, value, callback) => {
                var myReg = /[~!！@#$%^&*()/\|,<>?"'“‘();:+=\[\]{}]/;
                value = value.replace(/\s*/g,"");
                if(!value){
                    callback("请填写名字");
                }else{
                    if (myReg.test(value)) {
                        callback("名字不能包含特殊字符");
                    } else {
                        callback();
                    }
                }
            };
            const validateKafkaAddr = (rule, value, callback) => {
                var myReg = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}(\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5]))?$/;
                if (!value) {
                    callback();
                } else {
                    if (myReg.test(value)) {
                        callback();
                    } else {
                        callback("KAFKA配置地址格式不正确");
                    }
                }
            };
            const validatekafkaTopic = (rule, value, callback) => {
                // 配置了kafka路径后，必须配置topic
                if (this.formValidate.kafka_addr) {
                    if(!value || !value.trim()){
                        callback('配置了kafka路径后，必须配置topic');
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            };
            return{
                options3: {
                    disabledDate (date) {
                        return date && date.valueOf() > Date.now();
                    },
                    shortcuts: [
                        {
                            text: '近一周',
                            value () {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                                return [start, end];
                            }
                        },
                        // {
                        //     text: '近一个月',
                        //     value () {
                        //         const end = new Date();
                        //         const start = new Date();
                        //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        //         return [start, end];
                        //     }
                        // },
                        // {
                        //     text: '近三个月',
                        //     value () {
                        //         const end = new Date();
                        //         const start = new Date();
                        //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        //         return [start, end];
                        //     }
                        // }
                    ]
                },
                configerItemPage:10,
                connfigerCurrentPage:1,
                btnNameValue:'',
                tbTitle: [
                    {
                        title:'序号',
                        type:'index',
                        width:60,
                        align:'center',

                    },
                    { title: '名称', key: 'name',align:'center',minWidth:100,tooltip: true
                        // render: (h, params) => {
                        //     return h('div', [
                        //         h('a', {
                        //             props: {size: 'small'},
                        //             style: {marginRight: '5px'},
                        //             on: {
                        //                     click: () => {
                        //                         this.getConfigureInfo(params)
                        //                 }
                        //             }
                        //         }, params.row.name)
                        //     ]);
                        // }
                    },
                    { title: '操作系统', key: 'osType',minWidth:100,align:'center',tooltip:true},
                    {
                        title:'路径',
                        key:'',
                        align:'center',
                        minWidth:100,
                        render: (h, params) => {
                            return h(TableTooltip, {
                                props: {
                                    content: params.row.data.path,
                                    width: 100,
                                    placement: 'bottom'
                                }
                            });
                        }
                        // render:(h,params)=>{
                        //     console.log(params.row)
                        //     return h('div',{},params.row.data.path)
                        // }
                    },
                    // {
                    //     title:'kafka路径',
                    //     key:'',
                    //     align:'center',
                    //     render:(h,params)=>{
                    //         return h('div',{},params.row.data.kafka_addr)
                    //     }
                    // },
                    // {
                    //     title:'kafka topic',
                    //     key:'',
                    //     align:'center',
                    //     render:(h,params)=>{
                    //         return h('div',{},params.row.data.kafka_topic)
                    //     }
                    // },
                    {
                        title:'读取周期(/S)',
                        key:'',
                        align:'center',
                        minWidth:100,
                        render:(h,params)=>{
                            return h(TableTooltip, {
                                props: {
                                    content: params.row.data.gap == '0' ? '单次读取任务': params.row.data.gap,
                                    width: 64,
                                    placement: 'bottom'
                                }
                            })
                        }
                        // render:(h,params)=>{
                        //     return h('div',{},params.row.data.gap == '0' ? '单次读取任务': params.row.data.gap)
                        // }
                    },
                    {
                        title: '可见性',
                        key: '',
                        align:'center',
                        minWidth:100,
                        render:(h,params)=>{
                            let visibilityValue = params.row.visibility;
                            if(visibilityValue=="public"){
                                visibilityValue = "公共"
                            }else if(visibilityValue=="share"){
                                visibilityValue = "共享"
                            }else if(visibilityValue=="private"){
                                visibilityValue = "私有"
                            }
                            return h('div',{},visibilityValue)
                        }
                    },
                    {
                        title: '创建时间',
                        key: 'createTime',
                        align:'center',
                        width:140,
                        tooltip: true
                    },
                    {
                        title: '创建者',
                        key: 'creatorName',
                        align:'center', 
                        minWidth:100,
                        tooltip: true
                        // render:(h,params)=>{
                        //     if(params.index==1){
                        //         return h('div',{}, '贾海林');
                        //     }else{
                        //         return h('div',{}, params.row.creatorName)
                        //     } 
                        // }
                    },
                    { 
                        title: '描述', 
                        key: 'description',
                        align:'center', 
                        minWidth:100,
                        render: (h, params) => {
                            return params.row.description ? h(TableTooltip, {
                            props: {
                                content: params.row.description,
                                placement: 'bottom'
                            }
                            }):h('span','无');
                        }
                    },
                    {
                        title: '操作',
                        key: 'operation',
                        align:'center',
                        width:200,
                        render: (h, params) => {
                            //  if(params.index==1){
                            //     return ;
                            // }else{
                            //     // return h('div',{}, params.row.creatorName)
                            // } 
                            return h("div",[
                                h('Poptip',{
                                    class:'l18',
                                    props:{
                                        confirm:true,
                                        title:"您确定要删除此配置吗？",
                                    },
                                    on:{
                                        'on-ok':()=>{
                                            this.removeInfo(params)
                                        },
                                        'on-cancel':()=>{
                                            
                                        }
                                    }
                                },[
                                  h('style', `
                                      .l18 .ivu-icon {
                                        left: 18px;
                                      }
                                    `),
                                    h('Button',{
                                    props:{
                                        type:'error',
                                        size:'small'
                                    },
                                    style:{
                                        margin:'5px'
                                    },
                                    },'删除配置')]),
                                h('Button',{
                                    props:{
                                        type:"primary",
                                        size:'small'
                                        // style:{margin:'10px'}
                                    },
                                    style:{
                                        margin:'5px'
                                    },
                                    on:{
                                        click:()=>{
                                            this.modifyInfo(params)
                                        }
                                    }
                                },'修改配置')
                            ])
                        }
                    }
                ],
                formValidate: {
                    name: '',
                    osType: 'Windows',
                    path: '',
                    kafka_addr: '',
                    kafka_topic: '',
                    // read_way:'0',
                    gap: '5',
                    description: '',
                    visibility:'share',
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '', trigger: 'blur',validator:validateName }
                    ],
                    osType: [
                        { required: true, message: '请选择操作系统类型！', trigger: 'change' }
                    ],
                    path: [
                        { required: true, message: '请填写读取路径！', trigger: 'blur' }
                    ],
                    kafka_addr: [
                        { trigger: 'blur', validator: validateKafkaAddr }
                    ],
                    kafka_topic: [
                        { trigger: 'blur', validator: validatekafkaTopic }
                    ]
                    // kafka_addr: [
                    //     { required: true, message: 'kafka_addr不能为空！', trigger: 'blur' }
                    // ],
                    // kafka_topic: [
                    //     { required: true, message: 'kafka_topic不能为空！', trigger: 'change' }
                    // ],
                    // read_way:[
                    //     { required: true, message: '请选择一个读取方式！', trigger: 'change' }
                    // ]
                },
                tbData: [],
                detailTbData:[],
                loading: true,
                addConfigureBt: false,
                addConfigureBtTitle: '新增配置',
                currPage: 1,
                pageCount: 0,
                detailConfigureMd: false,
                detailTbTitle:[{
                    title:"属性",key:"attr"
                },{
                    title:"值",key:"value"
                }],
                configureDetailInfo:{},
                delConfigureMd: false,
                currConfigureId: '',
                currConfigureName: '',
                configerSystypeOfReach:'',
                configerStartTime:'',
                configerEndTime:'',
                configerDateSelected:'',
                timeInterval:0,
                configerTimeIntervalOfReach:'',
            }
        },
        props: ['readType','refreshTaskList'],
        created: function () {
            // this.tableHeight = $(window).height() - 115 ;
            if(this.readType == 'qga_loop_read'){
                this.ruleValidate.gap=[{ required: true, message: '请选择一个读取周期！', trigger: 'change' }]
            }
            this.getQgaReadLoopInfoList();
        },
        methods:{
            dateSelected(value){
                console.log(value);
                if(value[0]){
                    this.configerStartTime = String(value[0]) + ' 00:00:00';
                    this.configerEndTime =String( value[1]) + ' 23:59:59';
                    console.log(this.configerStartTime)
                }else{
                    this.configerStartTime = "";
                    this.configerEndTime = "";
                }
                this.connfigerCurrentPage=1;
                this.getQgaReadLoopInfoList();

            },
            change: function (page) {
                this.currPage = page;
                this.getQgaReadLoopInfoList();
            },
            getQgaReadLoopInfoList(){
                let _this = this;
                axios({
                    url: '/tasktemplate/item',
                    method: 'get',
                    params: {
                        page: _this.connfigerCurrentPage,
                        size: _this.configerItemPage,
                        operation: _this.readType,
                        name:_this.btnNameValue,
                        osType:_this.configerSystypeOfReach,
                        startTime:String(_this.configerStartTime),
                        endTime:String(_this.configerEndTime),
                        interval:_this.configerTimeIntervalOfReach
                    }
                }).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.info(response.message);
                        _this.tbData = [];
                    }else{
                         _this.tbData = response.data.list.map(function(item){
                             return {
                                id:item.id,
                                name:item.name,
                                osType:item.data.osType,
                                description:item.description,
                                data:item.data,
                                visibility:item.visibility,
                                createTime:item.createTime,
                                creatorName:item.creatorName
                             }
                         })
                         _this.pageCount = response.data.count;
                    }
                });
            },
            getConfigureInfo(params){
                let _this = this;
                _this.detailConfigureMd = true;
                _this.currConfigureId =  params.row.id;
                axios({
                    url: '/tasktemplate/item/' + _this.currConfigureId,
                    method: 'get',
                }).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.info(response.message);
                    }else{
                        _this.configureDetailInfo = response.data;
                        _this.detailTbData =  [
                                {attr:"名称",value: _this.configureDetailInfo.name},
                                {attr:"操作系统",value: _this.configureDetailInfo.data.osType},
                                {attr:"读取路径",value: _this.configureDetailInfo.data.path},
                                {attr:"kafka_addr",value: _this.configureDetailInfo.data.kafka_addr},
                                {attr:"kafka_topic",value: _this.configureDetailInfo.data.kafka_topic},
                                {attr:"读取周期",value: _this.configureDetailInfo.data.gap},
                                {attr:"配置描述",value: _this.configureDetailInfo.description},
                                {attr:"创建时间",value: _this.configureDetailInfo.createTime},
                                {attr:"创建者",value: _this.configureDetailInfo.creatorName},
                                {attr:"修改时间",value: _this.configureDetailInfo.lastModifyTime},
                                {attr:"修改者",value: _this.configureDetailInfo.modifior}
                             ]
                    }
                });
            },
            submitConfigureInfo(name){
                let _this = this;
                if(_this.readType == 'qga_loop_read' && (_this.formValidate.gap == null || _this.formValidate.gap == undefined ||_this.formValidate.gap == 0)){
                    _this.$Message.error('请选择一个读取周期！');
                    _this.loading = false;
                    _this.$nextTick(() => {
                        _this.loading = true;
                    });
                    return;
                }
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let data = _this.formValidate;
                        data.name = data.name.replace(/\s*/g,"");
                        if(_this.readType == 'qga_read'){
                            data.gap = null;
                        }
                        // 这两个属性保存时需要转义为接口要求的属性
                        data.kafkaAddress = data.kafka_addr
                        data.kafkaTopic = data.kafka_topic
                        if(_this.addConfigureBtTitle == '新增配置'){
                            axios({
                                url: '/tasktemplate/item/add/'+_this.readType,
                                method: 'post',
                                data:data
                            }).then(function (response) {
                                if(response.code != '1'){
                                    _this.$Message.error(response.message);
                                    _this.loading = false;
                                    _this.$nextTick(() => {
                                        _this.loading = true;
                                    });
                                }else{
                                    _this.$Message.success('新增配置完成!');  
                                    _this.loading = false;
                                    _this.$nextTick(() => {
                                        _this.loading = true;
                                    });
                                    _this.connfigerCurrentPage = 1
                                    _this.configerItemPage = 10
                                    _this.btnNameValue = ''
                                    _this.configerSystypeOfReach = ''
                                    _this.configerDateSelected = ''
                                    _this.configerStartTime = ''
                                    _this.configerEndTime = ''
                                    _this.configerTimeIntervalOfReach = ''
                                    _this.getQgaReadLoopInfoList();
                                    _this.addConfigureBt = false;
                                    _this.cancelsmtConfigureInfo('formValidate');
                                }
                                
                            });
                        }else{//修改配置
                            axios({
                                url: '/tasktemplate/item/update/' + _this.readType + '/'+_this.currConfigureId,
                                method: 'put',
                                data:data
                            }).then(function (response) {
                                if(response.code != '1'){
                                    _this.$Message.error(response.message);
                                    _this.loading = false;
                                    _this.$nextTick(() => {
                                        _this.loading = true;
                                    });
                                }else{
                                    _this.$Message.success('修改配置完成!');
                                    _this.loading = false;
                                    _this.$nextTick(() => {
                                        _this.loading = true;
                                    });
                                    _this.getQgaReadLoopInfoList();
                                    _this.addConfigureBt = false;
                                     _this.cancelsmtConfigureInfo('formValidate');
                                     _this.refreshTaskList();
                                }
                               
                                
                            });
                        }                       
                    } else {
                        _this.loading = false;
                        _this.$nextTick(() => {
                            _this.loading = true;
                        });
                        _this.$Message.info("请检查内容是否填写完整！");
                    }
                })
            },
            cancelsmtConfigureInfo(name){
                this.$refs[name].resetFields();
                this.formValidate = {
                    name: '',
                    osType: 'Windows',
                    path: '',
                    kafka_addr: '',
                    kafka_topic: '',
                    // read_way:'0',
                    gap: '5',
                    description: '',
                    visibility:'share',
                };
            },
            modifyInfo(params){
                let _this = this;
                _this.currConfigureId =  params.row.id;
                axios({
                    url: '/tasktemplate/item/' + _this.currConfigureId,
                    method: 'get'
                }).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.error(response.message);
                    }else{  
                        let way = response.data.data.gap.toString() == 0 ? '0' : '1';
                        console.log(way);
                        _this.formValidate ={
                            name: response.data.name,
                            osType: response.data.data.osType,
                            path: response.data.data.path,
                            kafka_addr: response.data.data.kafka_addr,
                            kafka_topic: response.data.data.kafka_topic,
                            gap: response.data.data.gap.toString(),
                            description: response.data.description,
                            visibility:response.data.visibility||'share',
                            read_way:way
                         };
                        _this.addConfigureBtTitle = "修改配置";
                        _this.addConfigureBt = true;
                    }
                });
            },
            removeInfo(params){
                this.currConfigureId =  params.row.id;
                this.ok4delConfigureMd()
            },
            ok4delConfigureMd(){
                let _this = this;
                axios({
                    url: '/tasktemplate/item/' + _this.currConfigureId,
                    method: 'delete'
                }).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.error(response.message);
                    }else{
                        _this.connfigerCurrentPage = (_this.tbData.length == 1 && _this.connfigerCurrentPage > 1) ?
                            _this.connfigerCurrentPage -1 : _this.connfigerCurrentPage;
                         _this.$Message.success("删除配置完成！");
                         _this.getQgaReadLoopInfoList();
                    }
                });
                _this.delConfigureMd = false;
            },
            switchineConfigerCurrentPage(numberPage){
                this.connfigerCurrentPage = numberPage;
                this.getQgaReadLoopInfoList()
            },
            switchConfigerItemPage(numberSize){
                this.configerItemPage = numberSize
                this.getQgaReadLoopInfoList()
            },
            handleEmpty(){
                this.btnNameValue = ''
                this.configerSystypeOfReach = ''
                this.configerDateSelected = ''
                this.configerEndTime = ''
                this.configerStartTime = ''
                this.getQgaReadLoopInfoList()
            }
        },
        watch:{
            
            // formValidate:{
            //     handler(newval,oldval){
            //         console.log(newval);
            //         if(newval.read_way == 1){
            //             this.ruleValidate['gap'] = [
            //                 { required: true, message: '请选择一个读取周期！', trigger: 'change' }
            //             ]
            //         }else{
            //             this.ruleValidate['gap'] = [
            //                 { required: false, message: '请选择一个读取周期！', trigger: 'change' }
            //             ]
            //         }
            //     },
            //     deep:true
            // }
        }
    }

</script>
